package com.zndroid.gridview.preview.indicator.impl;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.Nullable;

public class RoundLinesIndicator3rd extends View {
    private final int INDICATOR_NORMAL_COLOR = 0x88ffffff;
    private final int INDICATOR_SELECTED_COLOR = 0xFF03DAC5;

    int selectWidth = (int) dp2px(16);
    int radius = (int) dp2px(4);
    int height = (int) dp2px(4);

    protected Paint mPaint;
    private int count;
    private int index;

    public RoundLinesIndicator3rd(Context context) {
        this(context, null);
    }

    public RoundLinesIndicator3rd(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundLinesIndicator3rd(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(INDICATOR_NORMAL_COLOR);
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (count <= 1) {
            return;
        }
        setMeasuredDimension( selectWidth * count, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (count <= 1) {
            return;
        }

        mPaint.setColor(INDICATOR_NORMAL_COLOR);
        RectF oval = new RectF(0, 0, canvas.getWidth(), height);
        canvas.drawRoundRect(oval, radius, radius, mPaint);

        mPaint.setColor(INDICATOR_SELECTED_COLOR);
        int left = (int) (index * selectWidth);
        RectF rectF = new RectF(left, 0, left + selectWidth, height);
        canvas.drawRoundRect(rectF, radius, radius, mPaint);
    }

    private float dp2px(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
    }

    public void notifyChanged(int count, int index) {
        this.index = index;
        this.count = count;
        invalidate();
    }
}
